# crud.py
# 数据库操作函数，封装常用增删改查
from sqlalchemy.orm import Session
from models import User, Card, UserCard, Order, CartItem
from schemas import UserCreate, CardCreate, OrderCreate
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password: str) -> str:
    """密码加密"""
    return pwd_context.hash(password)

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

# 用户相关

def get_user_by_username(db: Session, username: str):
    return db.query(User).filter(User.username == username).first()

def get_user_by_email(db: Session, email: str):
    return db.query(User).filter(User.email == email).first()

def create_user(db: Session, user: UserCreate):
    hashed_password = get_password_hash(user.password)
    db_user = User(username=user.username, email=user.email, hashed_password=hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

# 卡牌相关

def get_card_by_code(db: Session, code: str):
    return db.query(Card).filter(Card.code == code).first()

def create_card(db: Session, card: CardCreate):
    db_card = Card(**card.dict())
    db.add(db_card)
    db.commit()
    db.refresh(db_card)
    return db_card

# 用户卡牌（出售）
def add_user_card(db: Session, user_id: int, card_id: int, quantity: int, price: float):
    db_user_card = UserCard(owner_id=user_id, card_id=card_id, quantity=quantity, price=price)
    db.add(db_user_card)
    db.commit()
    db.refresh(db_user_card)
    return db_user_card

# 订单相关

def create_order(db: Session, order: OrderCreate, buyer_id: int, seller_id: int, price: float):
    db_order = Order(
        buyer_id=buyer_id,
        seller_id=seller_id,
        user_card_id=order.user_card_id,
        quantity=order.quantity,
        total_price=price * order.quantity,
        status="pending"
    )
    db.add(db_order)
    db.commit()
    db.refresh(db_order)
    return db_order

# 购物车相关

def add_to_cart(db: Session, user_id: int, user_card_id: int, quantity: int):
    db_cart_item = CartItem(user_id=user_id, user_card_id=user_card_id, quantity=quantity)
    db.add(db_cart_item)
    db.commit()
    db.refresh(db_cart_item)
    return db_cart_item 